package com.nutransit;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.mylibrary.mylibrary.folding_layout.FoldingDrawerLayout;
import com.mylibrary.mylibrary.gps.GPSTracker;
import com.mylibrary.mylibrary.imageloader.ImageLoader;
import com.mylibrary.mylibrary.util.CommonCode;
import com.mylibrary.mylibrary.util.SessionData;
import com.nutransit.commoncode.Webservice_parametrs;
import com.nutransit.service.MyService;

public class MainActivity_Nutransit extends ActionBarActivity implements Webservice_parametrs, OnClickListener
{
	private FoldingDrawerLayout mDrawerLayout;
	private ActionBarDrawerToggle mDrawerToggle;
	private LinearLayout drawer_view;
	private ActionBar actionBar;
	private TextView tv_About_NuTransit, tv_Reserve_A_NuCab,
			tv_Reserve_A_NuVan, tv_Passengers_Bill_of_Rights,
			tv_Sharing_Rewards, tv_Blog;
	public static TextView tv_UserName;
	public static ImageView iv_Profile_Pict;

	private Context context;
	private Resources resources;
	private SessionData sessionData;
//	private ImageLoader imageLoader;

	public static String strUserType = "", strUserId = "";
	private Bundle bundle;
	public static JSONObject jsonObject_data = null;
	public static ArrayList<String> arrayList_ReservationIds;

	private GPSTracker gpsTracker;

	@SuppressLint("InlinedApi")
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		if(Build.VERSION.SDK_INT>=11)
			getWindow().requestFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
		setContentView(R.layout.activity_main);
		init_var();
	}

	private void init_var()
	{
		context = MainActivity_Nutransit.this;
		resources = context.getResources();
		sessionData = new SessionData(context, PACKAGE_NAME);
		actionBar = getSupportActionBar();
		gpsTracker = new GPSTracker(MainActivity_Nutransit.this);
		

		actionBar.setDisplayHomeAsUpEnabled(true);
		actionBar.setDisplayShowHomeEnabled(true);
		actionBar.setDisplayUseLogoEnabled(true);
		actionBar.setIcon(R.drawable.menu_navigation);
		actionBar.setBackgroundDrawable(new ColorDrawable(android.R.color.transparent));
		actionBar.setTitle("");

		strUserType = sessionData.getString(TAG_user_type);
		drawer_view = (LinearLayout) findViewById(R.id.drawer_view);
		mDrawerLayout = (FoldingDrawerLayout) findViewById(R.id.drawer_layout);

		tv_About_NuTransit = (TextView) findViewById(R.id.tv_About_NuTransit);
		tv_Reserve_A_NuCab = (TextView) findViewById(R.id.tv_Reserve_A_NuCab);
		tv_Reserve_A_NuVan = (TextView) findViewById(R.id.tv_Reserve_A_NuVan);
		tv_Passengers_Bill_of_Rights = (TextView) findViewById(R.id.tv_Passengers_Bill_of_Rights);
		tv_Sharing_Rewards = (TextView) findViewById(R.id.tv_Sharing_Rewards);
		tv_Blog = (TextView) findViewById(R.id.tv_Blog);
		tv_UserName = (TextView) findViewById(R.id.tv_UserName);
		tv_About_NuTransit.setOnClickListener(this);
		tv_Reserve_A_NuCab.setOnClickListener(this);
		tv_Reserve_A_NuVan.setOnClickListener(this);
		tv_Passengers_Bill_of_Rights.setOnClickListener(this);
		tv_Sharing_Rewards.setOnClickListener(this);
		tv_Blog.setOnClickListener(this);
		tv_UserName.setOnClickListener(this);

		iv_Profile_Pict = (ImageView) findViewById(R.id.iv_Profile_Pict);
		iv_Profile_Pict.setOnClickListener(this);

		if (mDrawerLayout != null)
		{
			mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);

			mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_transparent, R.string.app_name, R.string.app_name)
			{
				public void onDrawerClosed(View view)
				{
					actionBar.setIcon(R.drawable.menu_navigation);
					supportInvalidateOptionsMenu();
				}

				public void onDrawerOpened(View drawerView)
				{
					actionBar.setIcon(R.drawable.ic_back);
					supportInvalidateOptionsMenu();
				}
			};
			mDrawerLayout.setDrawerListener(mDrawerToggle);
		}
		if (strUserType.equalsIgnoreCase(TAG_user))
		{
			get_reservation_ids();
			Intent intent = getIntent();
			if (intent != null && intent.hasExtra(TAG_id))
			{
				String strId = intent.getStringExtra(TAG_id);
				if (arrayList_ReservationIds.contains(strId))
				{
					arrayList_ReservationIds.remove(strId);
					sessionData.setString(TAG_reservation_ids, new Gson().toJson(arrayList_ReservationIds));
					if (CommonCode.isMyServiceRunning(MyService.class, context))
					{
						context.stopService(new Intent(context, MyService.class));
					}
					if (arrayList_ReservationIds.size() > 0)
						context.startService(new Intent(context, MyService.class));
				}
			}
			displayView(0);
		}
		else
		{
			// if(!CommonCode.isMyServiceRunning(MyService.class, context))
			// context.startService(new Intent(context, MyService.class));
			findViewById(R.id.lLayout_User_Info).setVisibility(View.GONE);
			displayView(2);
		}
		// turnGPSOn();
		set_User_Data(sessionData.getString(TAG_data), context);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch (item.getItemId())
		{
		case android.R.id.home:
			if (mDrawerLayout.isDrawerOpen(Gravity.LEFT))
				mDrawerLayout.closeDrawer(Gravity.LEFT);
			else
				mDrawerLayout.openDrawer(Gravity.LEFT);
			break;
		case R.id.action_Profile:
			displayView(1);
			break;
		case R.id.action_Terms_and_Condition:
			displayView(8);
			break;
		case R.id.action_Privacy_Policy:
			displayView(9);
			break;
		case R.id.action_LogOut:
			log_Out_User();
			break;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	public static void set_User_Data(String strUerData, Context context)
	{
		try
		{
			System.out.println("==========strUserData:"+strUerData);
//			String strUerData = sessionData.getString(TAG_data);
			ImageLoader imageLoader = new ImageLoader(context);
			if (strUerData != null)
			{
				jsonObject_data = new JSONObject(strUerData);
				if (jsonObject_data != null)
				{
					tv_UserName.setText(jsonObject_data.has(TAG_username) ? "Hi " + jsonObject_data.getString(TAG_username) : "Hi Gest");
					strUserId = jsonObject_data.has(TAG_id) ? jsonObject_data.getString(TAG_id) : "";
					if (jsonObject_data.has(TAG_image))
					{
						String strImage = jsonObject_data.getString(TAG_image);
						if (strImage != null && strImage.length() > 0)
							imageLoader.DisplayImage(URL_IMAGE_URL + strImage, iv_Profile_Pict);
					}
				}
			}
		}
		catch (JSONException e)
		{
			e.printStackTrace();
		}
	}

	private void log_Out_User()
	{
		sessionData.setString(TAG_data, null);
		sessionData.setString(TAG_user_type, null);
		Toast.makeText(context, resources.getString(R.string.You_are_logout_successfully), Toast.LENGTH_SHORT).show();
		startActivity(new Intent(context, Login_Activity.class));
		if (CommonCode.isMyServiceRunning(MyService.class, context))
		{
			context.stopService(new Intent(context, MyService.class));
		}
		strUserType = null;
		MainActivity_Nutransit.this.finish();
	}

	private void get_reservation_ids()
	{
		String strReservationIds = sessionData.getString(TAG_reservation_ids);
		if (strReservationIds != null)
			arrayList_ReservationIds = CommonCode.convert_ArrayListString_To_Arraylist_for_string(strReservationIds);
		else
			arrayList_ReservationIds = new ArrayList<String>();
	}

	// private void turnGPSOn()
	// {
	// System.out.println("=====================turnGPSOn");
	// Intent intent=new Intent("android.location.GPS_ENABLED_CHANGE");
	// intent.putExtra("enabled", true);
	// sendBroadcast(intent);
	// // String provider = Settings.Secure.getString(getContentResolver(),
	// Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
	// //
	// // if(!provider.contains("gps")){ //if gps is disabled
	// // final Intent poke = new Intent();
	// // poke.setClassName("com.android.settings",
	// "com.android.settings.widget.SettingsAppWidgetProvider");
	// // poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
	// // poke.setData(Uri.parse("3"));
	// // sendBroadcast(poke);
	// // }
	// }

	/**
	 * When using the ActionBarDrawerToggle, you must call it during
	 * onPostCreate() and onConfigurationChanged()...
	 */
	@Override
	protected void onPostCreate(Bundle savedInstanceState)
	{
		super.onPostCreate(savedInstanceState);
		if (mDrawerLayout != null)
		{
			// Sync the toggle state after onRestoreInstanceState has occurred.
			mDrawerToggle.syncState();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(final Menu menu)
	{
		getMenuInflater().inflate(R.menu.main_menu, menu);
		return true;
	}

	/**
	 * Diplaying fragment view for selected nav drawer list item
	 * 
	 * @param isBackStackNull
	 * */
	private void displayView(int position)
	{
		// update the main content by replacing fragments
		Fragment fragment = null;
		switch (position)
		{
		case 0:
			fragment = new Fragment_Home();
			break;
		case 1:
			fragment = new Fragment_Update_Profile();
			break;
		case 2:
			fragment = new Fragment_User_Request();
			break;
		case 3:
			fragment = new Fragment_WebView();
			bundle = new Bundle();
			bundle.putString(TAG_page_content, URL_SHARING_REWARDS);
			fragment.setArguments(bundle);
			break;
		case 4:
			fragment = new Fragment_WebView();
			bundle = new Bundle();
			bundle.putString(TAG_pageid, "36");
			fragment.setArguments(bundle);
			break;
		case 5:
			fragment = new Fragment_WebView();
			bundle = new Bundle();
			bundle.putString(TAG_pageid, "38");
			fragment.setArguments(bundle);
			break;
		case 6:
			fragment = new Fragment_WebView();
			bundle = new Bundle();
			bundle.putString(TAG_page_content, URL_ABOUT_US);
			fragment.setArguments(bundle);
			break;
		case 7:
			fragment = new Fragment_van_route_selection();
			break;
		case 8:
			fragment = new Fragment_WebView();
			bundle = new Bundle();
			bundle.putString(TAG_page_content, URL_TERMS_AND_CONDITION);
			fragment.setArguments(bundle);
			break;
		case 9:
			fragment = new Fragment_WebView();
			bundle = new Bundle();
			bundle.putString(TAG_page_content, URL_PRIVACY_POLICY);
			fragment.setArguments(bundle);
			break;
		case 10:
			fragment = new Fragment_WebView();
			bundle = new Bundle();
			bundle.putString(TAG_page_content, URL_BILL_OF_RIGHT);
			fragment.setArguments(bundle);
			break;

		default:
			fragment = null;
			break;
		}

		if (fragment != null)
		{
			final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
			ft.add(R.id.fLayout_Container, fragment, "MyFragmentTag");
			if (position != 0 && position != 2)
				ft.addToBackStack(null);
			ft.commit();

			// update selected item and title, then close the drawer
			if (mDrawerLayout != null)
			{
				mDrawerLayout.closeDrawer(drawer_view);
			}
		}
	}

	@Override
	public void onClick(View view)
	{
		switch (view.getId())
		{
		case R.id.tv_About_NuTransit:
			displayView(6);
			break;
		case R.id.tv_Reserve_A_NuCab:
			displayView(7);
			break;
		case R.id.tv_Reserve_A_NuVan:
			displayView(7);
			break;
		case R.id.tv_Passengers_Bill_of_Rights:
			displayView(10);
			break;
		case R.id.tv_Sharing_Rewards:
			displayView(3);
			break;
		case R.id.tv_Blog:
			displayView(5);
			break;
		case R.id.tv_UserName:
			displayView(1);
			break;
		case R.id.iv_Profile_Pict:
			displayView(1);
			break;

		default:
			break;
		}
	}

//	@Override
//	public void onBackPressed()
//	{
//		AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity_Nutransit.this);
//		builder.setMessage("Do You Want To Exit This Application").setCancelable(false).setPositiveButton("Yes", new DialogInterface.OnClickListener()
//		{
//			public void onClick(DialogInterface dialog, int id)
//			{
//				MainActivity_Nutransit.this.finish();
//			}
//		}).setNegativeButton("No", new DialogInterface.OnClickListener()
//		{
//			public void onClick(DialogInterface dialog, int id)
//			{
//				dialog.cancel();
//			}
//		});
//		AlertDialog alert = builder.create();
//		alert.show();
//	}

}
